package redis

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

type Client struct {
	Client *redis.Client
}

func New(addr, pass string, db int) *Client {
	return &Client{
		Client: redis.NewClient(&redis.Options{
			Addr:     addr,
			Password: pass,
			DB:       db,
            PoolSize: 20,          // 连接池大小
            MinIdleConns: 5,       // 最小空闲连接
		}),
	}
}

// 添加延迟任务
func (c *Client) AddDelayTask(ctx context.Context, key string, taskID string, execTime time.Time) error {
	return c.Client.ZAdd(ctx, key, redis.Z{
		Score:  float64(execTime.Unix()),
		Member: taskID,
	}).Err()
}

// 获取到期任务
func (c *Client) GetDueTasks(ctx context.Context, key string) ([]string, error) {
	return c.Client.ZRangeByScore(ctx, key, &redis.ZRangeBy{
		Min: "0",
		Max: fmt.Sprintf("%d", time.Now().Unix()),
	}).Result()
}

// 删除已处理任务
func (c *Client) RemoveTask(ctx context.Context, key, taskID string) error {
	return c.Client.ZRem(ctx, key, taskID).Err()
}